import 'dart:async';
import 'dart:io';
import 'package:just_audio/just_audio.dart' as just_audio;
import 'package:just_audio/just_audio.dart';
import 'package:path_provider/path_provider.dart';
import 'package:record/record.dart';

class MicUtil {
  static AudioPlayer player = AudioPlayer();

  /// 录音文件地址
  static String _audioUrl = "";

  /// 当前播放的音频文件地址
  static String currentSoundUrl = "";

  static StreamSubscription<just_audio.PlayerState>? _playerStateSubscription;

  static AudioRecorder record = AudioRecorder();

  static Timer? _timer;

  static double _recordDuration = 0;

  static bool isRecording = false;

  /// 语音开始录制
  static micStart() async {
    if (await record.isRecording()) return;
    Directory tempDir = await getTemporaryDirectory();
    var time = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    _audioUrl = '${tempDir.path}/$time.m4a';
    _timer?.cancel();
    _recordDuration = 0;
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      _recordDuration++;
    });
    await record.start(const RecordConfig(), path: _audioUrl);
    isRecording = await record.isRecording();
  }

  /// 语音停止录制
  static micStop(Function(String micPath, double time) micData) async {
    if (!await record.isRecording()) return;
    await record.stop();
    isRecording = await record.isRecording();
    _timer?.cancel();
    // 获取录音文件秒数
    micData(_audioUrl, _recordDuration);
  }

  ///音频播放
  static playSound(
      String soundUrl, Function() playReady, Function() playFinish) async {
    if (player.playing) return;
    _playerStateSubscription = player.playerStateStream.listen((state) async {
      if (state.processingState == ProcessingState.ready) {
        // 准备播放
        currentSoundUrl = soundUrl;
        playReady();
      }
      if (state.processingState == ProcessingState.completed) {
        // 播放完成
        await player.stop();
        _playerStateSubscription?.cancel();
        _playerStateSubscription = null;
        currentSoundUrl = '';
        playFinish();
      }
    });
    if (soundUrl.contains('http')) {
      await player.setUrl(soundUrl);
    } else {
      await player.setFilePath(soundUrl);
    }
    await player.play();
    currentSoundUrl = soundUrl;
  }

  ///音频停止播放
  static stopSound(Function() playStop) async {
    if (!player.playing) return;
    await player.stop();
    _playerStateSubscription?.cancel();
    _playerStateSubscription = null;
    currentSoundUrl = '';
    playStop();
  }
}
